<template>
  <div class="channel-edit">
    <!-- 标题和编辑 -->
    <van-cell :border="false">
      <div slot="title" class="title-text">我的频道</div>
      <van-button type="danger" class="edit-btn"
      plain
      round
      size="mini"
      @click="isEdit = !isEdit"
      >{{ isEdit ? '完成' : '编辑'}}</van-button>
    </van-cell>
    <!-- 宫格内容标签 -->
    <van-grid class="my-grid" :gutter="10">
      <van-grid-item v-for="(channel,index) in myChannels"
      :key="index"
      class="grid-item"
      @click="onMychannelClick(channel,index)"
      >
      <van-icon slot="icon"
      name="clear"
      v-show="isEdit && !fixChannels.includes(channel.id)"
      ></van-icon>
    <span slot="text" class="text"
    :class="{active: index === active}"
    >{{channel.name}}</span>
    </van-grid-item>
    </van-grid>

    <!-- p频道推荐 -->
    <!-- 标题和编辑 -->
      <van-cell :border="false">
        <div slot="title" class="title-text">频道推荐</div>

      </van-cell>
      <!-- 宫格内容标签 -->
      <van-grid class="recommed-grid" :gutter="10">
        <van-grid-item v-for="(channel,index) in recommendChannels"
        :key="index"
        class="grid-item"
        icon="plus"
        :text="channel.name"
        @click="onAddChannel(channel)"
        />
      </van-grid>
    <!-- p频道推荐 -->

  </div>
</template>

<script>
import { getAllChannels, addUserChannel, deleteUserChannel } from '@/api/channel'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  name: 'ChannelEdit',
  props: {
    myChannels: {
      type: [Object, Array],
      require: true
    },
    active: {
      type: Number,
      require: true
    }
  },
  data () {
    return {
      allchannels: [],
      isEdit: false, // 控制编辑状态的显示
      fixChannels: [0] // 顾定频道，不允许删除
    }
  },
  created () {
    this.loadAllChannels()
  },
  methods: {
    async loadAllChannels () {
      try {
        const { data } = await getAllChannels()
        this.allchannels = data.data.channels
      } catch (error) {
        this.$toast('数据获取失败')
      }
    },
    // 添加标签
    async onAddChannel (channel) {
      // eslint-disable-next-line vue/no-mutating-props
      this.myChannels.push(channel)
      // 数据持久化处理
      if (this.user) {
        // 已登录，把数据请求接口放到线上
        try {
          await addUserChannel({
            id: channel.id, // 频道ID
            seq: this.myChannels.length // 序号
          })
        } catch (err) {
          this.$toast('保存失败')
          console.log(err.message)
        }
      } else {
        // 未登录，把数据存储到本地
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },
    onMychannelClick (channel, index) {
      // 编辑状态执行删除频道
      if (this.isEdit) {
        // 如果是固定频道，则不删除
        if (this.fixChannels.includes(channel.id)) {
          return
        }
        // 编辑状态执行删除频道
        // eslint-disable-next-line vue/no-mutating-props
        this.myChannels.splice(index, 1)
        // 如果删除的激活频道之前的频道。则更新激活频道项
        if (index <= this.active) {
          this.$emit('update-active', this.active - 1, true)
        }
        // 处理持久化
        this.deteleChannel(channel)
      } else {
        // 非编辑状态，执行切换频道
        this.$emit('update-active', index, false)
      }
    },
    // 删除频道
    async deteleChannel (channel) {
      // 已登录，将数据更新到线上
      if (this.user) {
        // 已登录数据同步到线上
        try {
          await deleteUserChannel(channel.id)
        } catch (error) {
          this.$toast('操作失败')
        }
      } else {
        // 未登录，放到本地存储
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    }
  },
  computed: {
    ...mapState(['user']),
    recommendChannels () {
      const channels = []
      this.allchannels.forEach(channel => {
        const ret = this.myChannels.find(myChannel => {
          return myChannel.id === channel.id
        })
        // 如果我的频道中不包括该频道，则收集到频道推荐中去
        if (!ret) {
          channels.push(channel)
        }
      })
      return channels
    }
  }
}
</script>

<style lang="less" scoped>
  .channel-edit {
    padding: 42.5px 0;
    .title-text {
      font-size: 16px;
      color: #333333;
    }
    .edit-btn {
      width: 52px;
      height: 24px;
      font-size: 13px;
      color: #f85959;
      border: 1px solid #f85959;
    }
   /deep/ .grid-item {
      width: 80px;
      height: 44px;
      .van-grid-item__content{
        white-space: nowrap;
        background-color: #f4f5f6;
        .van-grid-item__text, .text {
          font-size: 14px;
          color: #222;
          margin-top: 0;
        }
        .active {
          color: red;
        }
        .van-grid-item__icon-wrapper {
          position: unset;
        }
      }
    }
    /deep/ .my-grid {
      .grid-item {
        .van-icon-clear {
          position: absolute;
          right: -6px;
          top: -5px;
          font-size: 15px;
          z-index: 2;
          color: gray;
        }
      }

    }
   /deep/ .recommed-grid {
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 16px;
          margin-right: 6px;
        }

      }
    }
  }
</style>
